package com.ncloud.aaaa.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.aaaa.model.UserRole;
import com.ncloud.aaaa.model.UserRolePK;
import com.ncloud.aaaa.repository.UserRoleRepository;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;

//import java.util.Optional;
@Service
public class RoleBusiServiceImpl{
	
	private static final Logger logger = LogManager.getLogger(RoleBusiServiceImpl.class);
	@Autowired
	private UserRoleRepository userRoleRepository;
	
	public void createUserRole(JSONObject json) {
		try {
			UserRolePK id = new UserRolePK();
			id.setUserId(json.getLong("userId"));
			id.setRoleId(json.getLong("roleId"));
			UserRole userRole = new UserRole();
			userRole.setId(id);
			userRoleRepository.save(userRole);
		} catch (Exception e) {
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		
	}

	public void deleteUserRole(JSONObject json) {
		try {
			Long userId = json.getLong("userId");
			List<UserRole> userRoles = userRoleRepository.findByUserId(userId);
			for (UserRole userRole : userRoles) {
				userRoleRepository.delete(userRole);
			}
		} catch (Exception e) {
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		
	}

	@Transactional
	public void updateUserRole(JSONObject json) {
		try {
			deleteUserRole(json);
			createUserRole(json);
		} catch (Exception e) {
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
	}
}
